package com.it.emall.controller;

import com.it.emall.domain.AdminUser;
import com.it.emall.mapper.UserMapper;
import com.it.emall.service.AdminUserService;
import com.it.emall.utils.JwtHelper;
import com.it.emall.utils.Md5;
import com.it.emall.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 后台登入认证接口
 */
@RestController
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminUserService adminUserService;

    @PostMapping("/login")
    public Object login(@RequestBody AdminUser adminUser){//接收参数形式的@RequestBody

        //调用service
        Map<String,Object> json= new HashMap<>();


        AdminUser loginuser = adminUserService.login(adminUser.getUsername());

        System.out.println(loginuser.getPassword());
        String s = Md5.md5(adminUser.getPassword());
        System.out.println(s);
        if(loginuser != null && loginuser.getPassword().equals(s)){
            System.out.println("登入成功");
            Map<String,Object> data = new HashMap<>();
            data.put("token",JwtHelper.createToken(loginuser.getUserId()));
            Map<String,Object> adminInfo = new HashMap<>();
            adminInfo.put("nikeName",loginuser.getUsername());
            adminInfo.put("avatar",loginuser.getAvatar());
            data.put("adminInfo",adminInfo);
            return ResponseUtils.ok(data);
        }else {
            System.out.println("失败");
            return ResponseUtils.fail(ResponseUtils.INVALID_TOKEN,"用户名或者密码错误");
        }

    }


    @GetMapping("/info")
    public Object info(@RequestHeader("token") String token){
        Integer userId = JwtHelper.verifyTokenAndGetUserId(token);
        AdminUser user = adminUserService.selectUserById(userId);
        Map<String,Object> data = new HashMap<>();
        data.put("name",user.getUsername());
        data.put("avatar",user.getAvatar());

        return ResponseUtils.ok(data);


    }
}
